from typing import Union, Dict, List
from urllib.parse import urlparse

# 传入 headers 字典，剔除 Playwright 不允许设置的字段，返回合法 headers。
def sync_headers(headers: Dict[str, str]) -> Dict[str, str]:
    forbidden = frozenset({
        'host', 'connection', 'content-length',
        'accept-encoding', 'upgrade-insecure-requests', 'cookie'
    })
    return {k: v for k, v in headers.items() if k.lower() not in forbidden}

# 支持传入 cookie 字符串或 headers 字典，统一返回 Playwright 格式的 cookie 列表。
def sync_cookies(headers_or_cookie: Union[str, Dict[str, str]], url: str, path: str = "/") -> List[Dict[str, str]]:
    # 提取域名
    parsed = urlparse(url)
    domain = parsed.hostname or "127.0.0.1"

    # 获取 cookie 字符串
    cookie_str = headers_or_cookie.get("cookie", "") if isinstance(headers_or_cookie, dict) else headers_or_cookie
    cookies = []

    for part in cookie_str.strip().split(";"):
        part = part.strip()
        if not part or "=" not in part:
            continue

        key, value = part.split("=", 1)
        cookies.append({
            "name": key.strip(),
            "value": value.strip().strip('"'),
            "domain": domain,
            "path": path
        })

    return cookies
